package com.dc.business.datacollectbusiness.thread;

import com.dc.business.datacollectbusiness.mapper.HJ212ReceiverMapper;
import com.dc.business.datacollectbusiness.model.HJ212Model;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

// HJ212报文协议接收线程类
@Slf4j
public class HJ212ReceiverThread extends Thread{

    private  String port;

    private  HJ212ReceiverMapper hj212ReceiverMapper;


    public HJ212ReceiverThread(String port, HJ212ReceiverMapper hj212ReceiverMapper) {
        this.port = port;
        this.hj212ReceiverMapper = hj212ReceiverMapper;
    }


    @Override
    public void run() {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(Integer.parseInt(port));
            log.info("服务器启动，监听端口：" + port);
        } catch (IOException e) {
            log.error("服务器启动错误：" + e.getMessage() + " ,端口号：" + port);
            return;
        }

        Socket clientSocket = null;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        try {
            serverSocket.setSoTimeout(8 * 60 * 1000);
            clientSocket = serverSocket.accept();
            serverSocket.setSoTimeout(3 * 60 * 1000);
            // 获取输入流
            if (clientSocket != null) {
                inputStream = clientSocket.getInputStream();
            }
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            }

            // 读取客户端发送的数据
            String message = null;
            if (bufferedReader != null) {
                message = bufferedReader.readLine();
            }

            if (message != null && message.length() > 6 && message.split(";").length == 15) {
                message = message.substring(0, message.length() - 6);
                String[] split = message.split(";");
                HJ212Model hj212Model = new HJ212Model();
                hj212Model.setPort(port);
                String[] splitMN = split[4].split("=");
                hj212Model.setMn(splitMN[1]);

                String[] splitTime = split[0].split("=");
                String detectTime = splitTime[1];
                String inputFormat = "yyyyMMddHHmmssSSS"; // 输入字符串的日期格式
                String outputFormat = "yyyy-MM-dd HH:mm:ss"; // 输出字符串的日期格式
                SimpleDateFormat inputSdf = new SimpleDateFormat(inputFormat);
                SimpleDateFormat outputSdf = new SimpleDateFormat(outputFormat);
                Date date = inputSdf.parse(detectTime); // 解析输入字符串为Date对象
                String formattedDate = outputSdf.format(date);
                hj212Model.setDetectTime(formattedDate);

                String[] split1 = new String[8];
                System.arraycopy(split, 7, split1, 0, 8);
                for (String string : split1) {
                    String[] split2 = string.split(",");
                    for (String s : split2) {
                        buildHJ212Model(s, hj212Model);
                    }
                }
                // 判断该mn上次插入信息时间与现在时间的间隔
                String lastDetectTime = hj212ReceiverMapper.findHJ212ByMn(hj212Model.getMn());
                if (lastDetectTime != null) {
                    hj212ReceiverMapper.insertHJ212Msg(hj212Model);
                    //log.info("端口: " + port + "对应设备更新捕获设备协议报文写入数据库...");
                    inputStream.close();
                    bufferedReader.close();
                    clientSocket.close();
                    serverSocket.close();
                } else {
                    hj212ReceiverMapper.insertHJ212Msg(hj212Model);
                    //log.info("端口: " + port + "对应设备第一次该捕获设备协议报文写入数据库...");
                    inputStream.close();
                    bufferedReader.close();
                    clientSocket.close();
                    serverSocket.close();
                }
            } else {
              log.error("端口" + port + "本次发送的message无效,错误信息:" + message);
              if (clientSocket != null) {
                  if (inputStream != null) {
                      inputStream.close();
                  }
                  if (bufferedReader != null) {
                      bufferedReader.close();
                  }
                  clientSocket.close();
                  serverSocket.close();
              }
            }
        } catch (SocketException e) {
            log.error("连接错误:" + e.getMessage());
        } catch (IOException e) {
            log.error("端口:" + port +"连接超时," + e.getMessage());
        } catch (ParseException e) {
            log.error("时间转换失败: " + e.getMessage());
        } finally {
            try {
                if (clientSocket != null) {
                    clientSocket.close();
                }
                serverSocket.close();
            } catch (IOException e) {
                log.error("服务器关闭失败: " + e.getMessage());
            }
        }
    }

    // 构造HJ212报文信息模型
    public static HJ212Model buildHJ212Model(String s, HJ212Model hj212Model){
        String[] split3 = s.split("=");
        if(split3[0].contains("d10801-Rtd")) {
            hj212Model.setVoltageC(split3[1]);
        } else if (split3[0].contains("d10801-Flag")) {

        } else if (split3[0].contains("d10601-Rtd")) {
            hj212Model.setVoltageA(split3[1]);
        } else if (split3[0].contains("d10601-Flag")) {

        } else if (split3[0].contains("d10401-Rtd")) {
            hj212Model.setTotalPower(split3[1]);
        } else if (split3[0].contains("d10401-Flag")) {

        } else if (split3[0].contains("d10501-Rtd")) {
            hj212Model.setTotalPowerConsumption(split3[1]);
        } else if (split3[0].contains("d10501-Flag")) {

        } else if (split3[0].contains("d10701-Rtd")) {
            hj212Model.setVoltageB(split3[1]);
        } else if (split3[0].contains("d10701-Flag")) {

        } else if (split3[0].contains("d10101-Rtd")) {
            hj212Model.setCurrentA(split3[1]);
        } else if (split3[0].contains("d10101-Flag")) {

        } else if (split3[0].contains("d10301-Rtd")) {
            hj212Model.setCurrentC(split3[1]);
        } else if (split3[0].contains("d10301-Flag")) {

        } else if (split3[0].contains("d10201-Rtd")) {
            hj212Model.setCurrentB(split3[1]);
        } else if (split3[0].contains("d10201-Flag")) {

        }

        else if(split3[0].contains("d20801-Rtd")) {
            hj212Model.setVoltageC(split3[1]);
        } else if (split3[0].contains("d20801-Flag")) {

        } else if (split3[0].contains("d20601-Rtd")) {
            hj212Model.setVoltageA(split3[1]);
        } else if (split3[0].contains("d20601-Flag")) {

        } else if (split3[0].contains("d20401-Rtd")) {
            hj212Model.setTotalPower(split3[1]);
        } else if (split3[0].contains("d20401-Flag")) {

        } else if (split3[0].contains("d20501-Rtd")) {
            hj212Model.setTotalPowerConsumption(split3[1]);
        } else if (split3[0].contains("d20501-Flag")) {

        } else if (split3[0].contains("d20701-Rtd")) {
            hj212Model.setVoltageB(split3[1]);
        } else if (split3[0].contains("d20701-Flag")) {

        } else if (split3[0].contains("d20101-Rtd")) {
            hj212Model.setCurrentA(split3[1]);
        } else if (split3[0].contains("d20101-Flag")) {

        } else if (split3[0].contains("d20301-Rtd")) {
            hj212Model.setCurrentC(split3[1]);
        } else if (split3[0].contains("d20301-Flag")) {

        } else if (split3[0].contains("d20201-Rtd")) {
            hj212Model.setCurrentB(split3[1]);
        } else if (split3[0].contains("d20201-Flag")) {

        }

        else if(split3[0].contains("d30801-Rtd")) {
            hj212Model.setVoltageC(split3[1]);
        } else if (split3[0].contains("d30801-Flag")) {

        } else if (split3[0].contains("d30601-Rtd")) {
            hj212Model.setVoltageA(split3[1]);
        } else if (split3[0].contains("d30601-Flag")) {

        } else if (split3[0].contains("d30401-Rtd")) {
            hj212Model.setTotalPower(split3[1]);
        } else if (split3[0].contains("d30401-Flag")) {

        } else if (split3[0].contains("d30501-Rtd")) {
            hj212Model.setTotalPowerConsumption(split3[1]);
        } else if (split3[0].contains("d30501-Flag")) {

        } else if (split3[0].contains("d30701-Rtd")) {
            hj212Model.setVoltageB(split3[1]);
        } else if (split3[0].contains("d30701-Flag")) {

        } else if (split3[0].contains("d30101-Rtd")) {
            hj212Model.setCurrentA(split3[1]);
        } else if (split3[0].contains("d30101-Flag")) {

        } else if (split3[0].contains("d30301-Rtd")) {
            hj212Model.setCurrentC(split3[1]);
        } else if (split3[0].contains("d30301-Flag")) {

        } else if (split3[0].contains("d30201-Rtd")) {
            hj212Model.setCurrentB(split3[1]);
        } else if (split3[0].contains("d30201-Flag")) {

        }
        return hj212Model;
    }

}
